from flask import render_template, current_app, session, request, jsonify

from info import redis_store, constants
from info.models import User, News, Category
from info.response_code import RET
from . import index_blu

@index_blu.route('/')
def index():
    # 获取当前登录用户的id
    user_id = session.get('user_id')
    # 通过id获取用户信息
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 右侧的新闻排行逻辑
    news_li = []
    try:
        news_li = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_li:
        news_dict_li.append(news.to_basic_dict())

    # 查询分类数据，返回给模板
    categories = []
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    category_li = []
    for category in categories:
        category_li.append(category.to_dict())

    data = {
        'user':user.to_dict() if user else None,
        'news_dict_li':news_dict_li,
        'category_li':category_li
    }


    return render_template('news/index.html',data=data)


# 在打开网页的时候，浏览器会默认去请求根路径+favicon.ico作为网站图标
@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')

@index_blu.route('/news_list')
def get_news_list():
    """
      获取指定分类的新闻列表
      1. 获取参数
      2. 校验参数
      3. 查询数据
      4. 返回数据
      :return:
      """
    # 1.获取参数
    cid = request.args.get('cid','1')
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')
    # 2.校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 3.查询数据
    filters = [News.status == 0]
    if cid != 1:  # 查询的不是最新的数据
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询错误')
    news_items = paginate.items  # 模型对象列表
    current_page = paginate.page
    total_page = paginate.pages

    # 将模型对象转成字典
    news_dict_li = []
    for news in news_items:
        news_dict_li.append(news.to_basic_dict())

    data = {
        'current_page':current_page,
        'total_page':total_page,
        'news_dict_li':news_dict_li
    }

    # 4.返回数据
    return jsonify(errno=RET.OK, errmsg="OK",data=data)



